import React, { useMemo } from 'react';
import { Input, Select, DatePicker, Form } from 'antd';
import SearchForm, { type SearchFormItem } from '@/components/SearchForm';
import DictionarySelect from '@/components/DictionarySelect';
import { useFieldOptions } from '@/hooks/useFieldOptions';
import type { FieldConfig, SearchDTO, FieldType } from './types';

const { RangePicker } = DatePicker;

// 选项选择组件（用于 API 和静态选项）
interface SelectFieldOptionsProps {
  field: FieldConfig;
  searchConfig: any;
  optionsConfig?: any;
}

const SelectFieldOptions: React.FC<SelectFieldOptionsProps> = ({ 
  field, 
  searchConfig, 
  optionsConfig 
}) => {
  const { options, loading } = useFieldOptions(optionsConfig);

  return (
    <Select
      placeholder={searchConfig.placeholder || `请选择${field.label}`}
      disabled={searchConfig.disabled}
      allowClear
      showSearch
      loading={loading}
      filterOption={(input, option) =>
        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
      }
      options={options}
      mode={searchConfig.searchType === 'in' ? 'multiple' : undefined}
    />
  );
};

interface DynamicSearchFormProps {
  fields: FieldConfig[];
  onSearch: (values: SearchDTO) => void;
  onReset?: () => void;
  loading?: boolean;
}

export const DynamicSearchForm: React.FC<DynamicSearchFormProps> = ({
  fields,
  onSearch,
  onReset,
  loading = false,
}) => {
  // 检查fields是否存在
  if (!fields || !Array.isArray(fields)) {
    return null;
  }
  
  // 转换为 SearchFormItem 格式
  const searchFormItems: SearchFormItem[] = useMemo(() => {
    // 筛选出可搜索的字段
    const searchableFields = fields.filter(field => field.search?.searchable);
    
    // 渲染搜索字段组件
    const renderSearchField = (field: FieldConfig): React.ReactNode => {
      const searchConfig = { ...field.common, ...field.search };
      const fieldType = field.type;

      switch (fieldType) {
        case 'text' as FieldType:
        case 'textarea' as FieldType:
          return (
            <Input
              placeholder={searchConfig.placeholder || `请输入${field.label}`}
              disabled={searchConfig.disabled}
              allowClear
            />
          );
        
        case 'number' as FieldType:
          return searchConfig.searchType === 'range' ? (
            <Input.Group compact>
              <Form.Item name={[field.key, 'min']} noStyle>
                <Input
                  style={{ width: '50%' }}
                  placeholder="最小值"
                  type="number"
                  disabled={searchConfig.disabled}
                />
              </Form.Item>
              <Form.Item name={[field.key, 'max']} noStyle>
                <Input
                  style={{ width: '50%' }}
                  placeholder="最大值"
                  type="number"
                  disabled={searchConfig.disabled}
                />
              </Form.Item>
            </Input.Group>
          ) : (
            <Input
              placeholder={searchConfig.placeholder || `请输入${field.label}`}
              type="number"
              disabled={searchConfig.disabled}
              allowClear
            />
          );
        
        case 'select' as FieldType:
          // 获取选项配置
          const optionsConfig = searchConfig.optionsConfig || 
            (searchConfig.options ? { source: 'static' as const, options: searchConfig.options } : undefined);
          
          // 如果使用字典
          if (optionsConfig?.source === 'dictionary' && optionsConfig.dictionaryCode) {
            return (
              <DictionarySelect
                code={optionsConfig.dictionaryCode}
                placeholder={searchConfig.placeholder || `请选择${field.label}`}
                disabled={searchConfig.disabled}
                allowClear
                showSearch
                mode={searchConfig.searchType === 'in' ? 'multiple' : undefined}
              />
            );
          }
          
          // 如果使用 API 或静态选项，使用 SelectFieldOptions 组件
          return (
            <SelectFieldOptions
              field={field}
              searchConfig={searchConfig}
              optionsConfig={optionsConfig}
            />
          );
        
        case 'date' as FieldType:
        case 'datetime' as FieldType:
          return searchConfig.searchType === 'range' ? (
            <RangePicker
              style={{ width: '100%' }}
              placeholder={['开始日期', '结束日期']}
              disabled={searchConfig.disabled}
              showTime={fieldType === ('datetime' as FieldType)}
            />
          ) : (
            <DatePicker
              style={{ width: '100%' }}
              placeholder={searchConfig.placeholder || `请选择${field.label}`}
              disabled={searchConfig.disabled}
              showTime={fieldType === ('datetime' as FieldType)}
            />
          );
        
        case 'switch' as FieldType:
        case 'radio' as FieldType:
          return (
            <Select
              placeholder={searchConfig.placeholder || `请选择${field.label}`}
              disabled={searchConfig.disabled}
              allowClear
              options={
                searchConfig.options || [
                  { label: '是', value: true },
                  { label: '否', value: false },
                ]
              }
            />
          );
        
        case 'checkbox' as FieldType:
          return (
            <Select
              mode="multiple"
              placeholder={searchConfig.placeholder || `请选择${field.label}`}
              disabled={searchConfig.disabled}
              allowClear
              options={searchConfig.options}
            />
          );
        
        default:
          return (
            <Input
              placeholder={searchConfig.placeholder || `请输入${field.label}`}
              disabled={searchConfig.disabled}
              allowClear
            />
          );
      }
    };

    return searchableFields.map(field => ({
      name: field.key,
      label: field.label,
      component: renderSearchField(field),
      col: field.search?.colSpan || 6,
    }));
  }, [fields]);

  // 处理搜索
  const handleSearch = (values: any) => {
    // 过滤掉空值
    const filteredValues: SearchDTO = {};
    Object.keys(values).forEach(key => {
      const value = values[key];
      if (value !== undefined && value !== null && value !== '') {
        // 处理范围查询
        if (typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)) {
          if (value.min !== undefined || value.max !== undefined) {
            filteredValues[key] = value;
          }
        } else if (Array.isArray(value) && value.length > 0) {
          filteredValues[key] = value;
        } else {
          filteredValues[key] = value;
        }
      }
    });
    
    onSearch(filteredValues);
  };

  // 处理重置
  const handleReset = () => {
    onReset?.();
    onSearch({});
  };

  if (searchFormItems.length === 0) {
    return null;
  }

  return (
    <SearchForm
      items={searchFormItems}
      onSearch={handleSearch}
      onReset={handleReset}
      loading={loading}
      defaultExpanded={false}
    />
  );
};

export default DynamicSearchForm;
